#include <iostream>
using namespace std;

#include <purewell/pipe.hpp>
using namespace purewell;

#include <sys/wait.h>
#include <fcntl.h>

void
testUnnamedPipe(void)
{
	PWPipe pipe;
	if ( !pipe.initialize() )
	{
		cerr << "failed to init pipe." << endl;
		return;
	}

	if ( fork() )
	{
		char buf[] = "Hello, world!";
		pipe.write(buf, sizeof(buf));
		int res;
		wait(&res);
		pipe.destroy();
		cerr << "Pipe is destroyed..." << endl;
	}
	else
	{
		char buf[1024];
		pipe.read(buf, sizeof(buf));
		cerr << "Unnamed pipe: " << buf << endl;
		exit(0);
	}
}

void
testNamedPipe(void)
{
	const char pipename[] = "pipetest.pipe";
	if ( fork() )
	{
		PWNamedPipe pipe;
		unlink(pipename);
		do
		{
			if ( !pipe.initialize(pipename,
				O_CREAT|O_WRONLY|O_EXCL, 0700) )
			{
				cerr << "failed to create pipe" << endl;
				break;
			}

			char buf[] = "Hello, world!";
			pipe.write(buf, sizeof(buf));
		} while (false);

		int res;
		wait(&res);

		cerr << "Pipe is destroyed..." << endl;
		pipe.destroy();

		unlink(pipename);
	}
	else
	{
		sleep(1);
		PWNamedPipe pipe;
		if ( !pipe.initialize(pipename,
			O_RDONLY, 0700) )
		{
			cerr << "failed to create pipe" << endl;
			exit(0);
		}

		char buf[1024];
		pipe.read(buf, sizeof(buf));
		cerr << "Named pipe: " << buf << endl;
		exit(0);
	}
}

int
main(int argc, char* argv[])
{
	testUnnamedPipe();
	testNamedPipe();
	return 0;
}

